package cn.laixueit.controller;

import cn.laixueit.pojo.User;
import cn.laixueit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public @ResponseBody
    List<User> list(){
        return userService.list();
    }

    @GetMapping("/sendMail")
    public @ResponseBody Boolean sendMail(String email, HttpServletRequest request){
        Integer code = userService.sendMail(email);
        if(code == null){
            return false;
        }
        HttpSession session = request.getSession();
        session.setAttribute(email+"emailCode",code);
        return true;
    }

    @PostMapping("/register")
    public @ResponseBody Boolean register(User user,Integer code,HttpServletRequest request){

        String email = user.getEmail();
        HttpSession session = request.getSession();
        Integer sessionCode = (Integer) session.getAttribute(email+"emailCode");
        if(sessionCode == null){
            return false;
        }
        if(!sessionCode.equals(code)){
            return false;
        }
        Boolean boo = userService.register(user);
        if(boo){
            session.removeAttribute(email+"emailCode");
        }
        return boo;
    }

    //修改密码的，参数只需要新的密码和账号
    //@GetMapping("/updatePwd")


    @GetMapping("/login")
    public String login(@RequestParam(required = true) String username,
                        @RequestParam String password,
                        HttpServletRequest request){
        Boolean status = userService.login(username,password);
        if(status){
            HttpSession session = request.getSession();
            session.setAttribute("username",username);
        }
        return status?"redirect:/home.jsp":"redirect:/login.jsp?error=true";
    }

    @GetMapping("/getUser")
    public @ResponseBody User getUser(HttpServletRequest request){
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if(StringUtils.isEmpty(username)){
            return null;
        }
        User user = userService.getUser(username);
        return user;
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("username");
        return "redirect:/login.jsp";
    }

}
